<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>5-draw</title>
    <script src="./js/d3.min.js"></script>
</head>
<style>
    svg rect {
        fill: gray;
    }

    svg text {
        fill: yellow;
        font: 12px sans-serif;
        text-anchor: end;
    }
</style>

<body>

</body>
<script>
    var data = [10, 5, 12, 15];
    var width = 300,
        scaleFactor = 20,
        barHeight = 30;

    var graph = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", barHeight * data.length);

    // 将data数据添加给g标签当中，并且设置其纵坐标累加
    var bar = graph.selectAll("g")
        .data(data)
        .enter()
        .append("g")
        .attr("transform", function (d, i) {
            return "translate(0," + i * barHeight + ")";
        });

    // 添加矩形
    bar.append("rect")
        .attr("width", function (d) {
            return d * scaleFactor;
        })
        .attr("height", barHeight - 1);

    // 将对应的数字值渲染上去
    bar.append("text")
        .attr("x", function (d) { return (d * scaleFactor); })
        .attr("y", barHeight / 2)
        .attr("dy", ".35em")
        .text(function (d) { return d; });
</script>

</html>